function mergeObjects<T extends Record<string, any>>(oldObj: T, newObj: Partial<T>): T {
  for (let key in newObj) {
    const newValue = newObj[key] as T[Extract<keyof T, string>] // 类型断言确保不会是 undefined
    if (oldObj.hasOwnProperty(key)) {
      if (isObject(oldObj[key]) && isObject(newValue)) {
        // 如果都是对象，则递归合并
        oldObj[key] = mergeObjects(oldObj[key], newValue)
      } else if (isArray(oldObj[key]) && isArray(newValue)) {
        // 如果都是数组，则合并数组元素
        oldObj[key] = oldObj[key].concat(newValue)
      } else {
        // 否则直接替换为新值
        oldObj[key] = newValue
      }
    } else {
      oldObj[key] = newValue
    }
  }

  return oldObj
}

function isObject(obj: object) {
  return obj !== null && typeof obj === 'object' && !Array.isArray(obj)
}

function isArray(arr: object) {
  return Array.isArray(arr)
}

export { mergeObjects }
